﻿using System.Buffers;
using System.Collections.Generic;
using Xc.DataAccess.Core.Extensions;
using System.Linq;
using System.Text.Json.Serialization;

namespace Xc.DataAccess.Protocoals.WaterMeters.Models
{
    public abstract class MeterFrameTxBase : MeterFrameTx
    {
        /// <summary>
        /// 完整类型名称
        /// </summary>
        public string FullTypeName
        {
            get
            {
                return this.GetType().FullName;
            }
        }
        /// <summary>
        /// 命令唯一序号
        /// </summary>
        public string CommandType 
        {
            get
            {
               return DevcieId+((byte)Cmd * 0x10000 + (ushort)DataSegment).ToString();
            }
        }
        internal void Option(string devcieId, MeterType meterType, byte companyId)
        {
            DevcieId = devcieId;
            this.MeterType = meterType;
            CompanyId = companyId;
        }
        [JsonIgnore]
        internal protected abstract DataSegment DataSegment { get; }
        /// <summary>
        /// 厂商ID
        /// </summary>
        [JsonIgnore]
        public byte CompanyId { get; internal set; } = 0;
        /// <summary>
        /// 设备编号
        /// </summary>
        public string DevcieId { get; set; } = "00000000000000";
        protected override ReadOnlySequence<byte> MeterAddress
        {
            get
            {
                return new ReadOnlySequence<byte>(DevcieId.ToHex());
            }
        }
        protected override DataArea DataArea 
        {
            get
            {
                List<byte> vs = new List<byte>();
                var buffer1= ((ushort)DataSegment).FromUInt16LittleEndian();
                vs.AddRange(buffer1);
                vs.Add(CompanyId);
                GetDataArea(vs);
                var check= ((ushort)vs.Sum(p => p)).FromUInt16LittleEndian();
                vs.AddRange(check);
                return DataArea.FromSequence(new ReadOnlySequence<byte>(vs.ToArray()));
            }
        }
        protected abstract void GetDataArea(List<byte> vs);
    }
}
